<template>
  <el-row>
    <el-col :span="3"></el-col>
    <el-col :span="4">
      <el-card
        style="
          margin: -5px 5px;
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          border-radius: 10px;
        "
      >
        <div
          style="
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
          "
        >
          个人主页
        </div>
        <div
          v-for="link in links"
          :key="link.path"
          style="text-align: left; margin-bottom: 10px"
        >
          <a
            class="Afont"
            :style="linkStyle"
            @click="goTo(link.path)"
            @mouseover="highlight($event)"
            @mouseout="unhighlight($event)"
            style="font-size: 16px; font-weight: 500; color: #007bff"
          >
            <el-icon><component :is="link.icon" /></el-icon> {{ link.text }}
          </a>
        </div>
      </el-card>
    </el-col>
    <el-col :span="10">
      <el-card
        v-if="!isEditing && currentPage !== 'announcement'"
        style="margin: -5px 5px; height: auto; width: 100%"
      >
        <img
          src="@/assets/1.jpg"
          alt="描述文字"
          style="width: 100%; height: 100%; margin: 0"
        />
        <el-row>
          <div class="demo-type">
            <div>
              <el-avatar
                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                style="width: 100px; height: 100px"
              />
              <p>v</p>
            </div>
          </div>
          <div>
            <p
              style="
                white-space: pre-wrap;
                font-size: 24px;
                color: #333;
                font-weight: bold;
                font-family: 'Brush Script MT', cursive;
              "
            >
              {{ userInfo?.username }}
            </p>
            <p style="white-space: pre-wrap">
              <a>学号 ：{{ userInfo?.usernum }} -- </a>
              <a>手机号：{{ userInfo?.userPhone }}</a> --
              <a>邮箱：{{ userInfo?.useremail }}</a>
            </p>
          </div>
        </el-row>
      </el-card>
      <el-card
        v-else-if="isEditing"
        class="info-card"
        shadow="hover"
        style="zoom: 1.5"
      >
        <div class="title">
          <p>个人信息管理</p>
        </div>
        <div class="info-row">
          <el-avatar
            :src="user.userimage"
            class="avatar"
            @click="showAvatarCard = true"
          ></el-avatar>
        </div>
        <br />
        <div class="info-row">
          <span v-if="!isEditingUsername" class="info-label"
            >用户名: {{ user.username }}</span
          >
          <div v-if="isEditingUsername" class="edit-row">
            <span class="edit-label">用户名:</span>
            <el-input
              v-model="user.username"
              placeholder="请输入用户名"
              class="el-input"
            ></el-input>
          </div>
          <el-button
            v-if="!isEditingUsername"
            type="warning"
            @click="isEditingUsername = true"
            >编辑</el-button
          >
          <el-button
            v-if="isEditingUsername"
            type="success"
            @click="saveUsername"
            >保存</el-button
          >
        </div>
        <br />
        <div class="info-row">
          <span class="info-label">学号: {{ user.usernum }}</span>
          <el-button type="danger" plain disabled>编辑</el-button>
        </div>
        <br />
        <div class="info-row">
          <span v-if="!isEditingPhone" class="info-label"
            >手机号码: {{ user.userPhone }}</span
          >
          <div v-if="isEditingPhone" class="edit-row">
            <span class="edit-label">手机号码:</span>
            <el-input
              v-model="user.userPhone"
              placeholder="请输入手机号码"
              class="el-input"
            ></el-input>
          </div>
          <el-button
            v-if="!isEditingPhone"
            type="warning"
            @click="isEditingPhone = true"
            >编辑</el-button
          >
          <el-button v-if="isEditingPhone" type="success" @click="saveUserPhone"
            >保存</el-button
          >
        </div>
        <br />
        <div class="info-row">
          <span v-if="!isEditingEmail" class="info-label"
            >邮箱: {{ user.useremail }}</span
          >
          <div v-if="isEditingEmail" class="edit-row">
            <span class="edit-label">邮箱:</span>
            <el-input
              v-model="user.useremail"
              placeholder="请输入邮箱"
              class="el-input"
            ></el-input>
          </div>
          <el-button
            v-if="!isEditingEmail"
            type="warning"
            @click="isEditingEmail = true"
            >编辑</el-button
          >
          <el-button v-if="isEditingEmail" type="success" @click="saveUserEmail"
            >保存</el-button
          >
        </div>
        <br />
        <div class="info-row">
          <el-button @click="showPasswordCard = true" class="center-button"
            >修改密码</el-button
          >
          <el-button @click="goBack" class="center-button">返回</el-button>
        </div>
        <br />
      </el-card>
      <el-card v-if="showAvatarCard" class="avatar-card">
        <el-form-item label="当前头像">
          <el-avatar :src="user.userimage" class="avatar"></el-avatar>
        </el-form-item>
        <el-form-item label="更改头像">
          <el-upload
            action="http://localhost:8000/UserController/updateUserImage"
            list-type="picture-card"
            :show-file-list="false"
            :data="{ userID: user.userID }"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="saveUserImage"
            :with-credentials="true"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="showAvatarCard = false">取消</el-button>
        </el-form-item>
      </el-card>
      <el-card v-if="showPasswordCard" class="password-card">
        <el-form-item label="旧密码">
          <el-input
            v-model="oldPassword"
            placeholder="旧密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input
            v-model="newPassword"
            placeholder="新密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="changePassword">保存</el-button>
          <el-button @click="showPasswordCard = false">取消</el-button>
        </el-form-item>
      </el-card>
      <el-card
        v-if="currentPage === 'announcement'"
        style="
          margin: -5px 5px;
          height: auto;
          width: 100%;
          border-left: 1px solid #ddd;
          border-right: 1px solid #ddd;
        "
      >
        <Notice />
      </el-card>
    </el-col>
    <el-col :span="4">
      <el-card style="margin: -5px 15px">
        <div>
          <span><b>你可能感兴趣的场地</b></span>
          <el-divider></el-divider>
          <span>羽毛球</span>
          <el-divider></el-divider>
          <span>篮球</span>
        </div>
      </el-card>
    </el-col>
    <el-col :span="3"></el-col>
  </el-row>
</template>

<script setup>
import { useRouter } from "vue-router";
import axios from "axios";
import { ref, onMounted, watch } from "vue";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const userInfo = ref({});
const router = useRouter();
const currentPage = ref("");
const linkStyle = {
  fontSize: "40px",
  fontWeight: "400",
  display: "inline-block",
  padding: "10px",
  color: "#000",
  textDecoration: "none",
  transition: "color 0.3s",
};
const links = [
  { path: "home", icon: "HomeFilled", text: "主页" },
  { path: "UserProfile", icon: "Edit", text: "信息修改" },
  { path: "Record", icon: "Bell", text: "预定" },
  { path: "following", icon: "StarFilled", text: "关注" },
  { path: "favorites", icon: "FolderAdd", text: "收藏" },
  { path: "frequent", icon: "LocationInformation", text: "经常访问" },
  { path: "creator", icon: "Memo", text: "预定记录" },
];

function goTo(path) {
  try {
    if (path === "UserProfile") {
      isEditing.value = true;
    } else {
      currentPage.value = path;
      router.push({ name: path });
    }
  } catch (error) {
    console.error("导航失败:", error);
  }
}

function highlight(event) {
  event.target.style.color = "#ff0000";
}

function unhighlight(event) {
  event.target.style.color = "#000";
}

onMounted(async () => {
  try {
    const res = await axios.get("http://localhost:8000/Login/check", {
      withCredentials: true,
    });
    const data = res.data;
    if (data.code == 0 && data.data.status == 1) {
      userInfo.value = data.data.userInfo;
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
});

const user = ref({
  userimage: "",
  username: "",
  usernum: "",
  userPhone: "",
  useremail: "",
});

const oldPassword = ref("");
const newPassword = ref("");
const isEditingUsername = ref(false);
const isEditingPhone = ref(false);
const isEditingEmail = ref(false);
const showAvatarCard = ref(false);
const showPasswordCard = ref(false);
const isEditing = ref(false);

const fetchUserData = () => {
  axios
    .get("http://localhost:8000/UserController/getUser", {
      withCredentials: true,
    })
    .then((response) => {
      console.log("接收到的用户数据:", response.data);
      user.value = response.data;
      if (user.value.userimage) {
        user.value.userimage = "data:image/jpeg;base64," + user.value.userimage;
      }
    })
    .catch((error) => {
      console.error("获取用户数据失败:", error);
    });
};

const handlePictureCardPreview = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    user.value.userimage = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

const handleRemove = (file, fileList) => {
  console.log("文件已移除:", file, fileList);
  user.value.userimage = "";
};

const saveUserImage = (response, file) => {
  console.log("头像已更新:", response);
  user.value.userimage = URL.createObjectURL(file.raw);
  showAvatarCard.value = false;
  ElMessage.success("头像已更新");
};

const saveUsername = () => {
  axios
    .post(
      "http://localhost:8000/UserController/updateUser",
      {
        username: user.value.username,
      },
      { withCredentials: true }
    )
    .then((response) => {
      console.log("用户名已更新:", response.data);
      isEditingUsername.value = false;
      ElMessage.success("用户名已更新");
    })
    .catch((error) => {
      console.error("更新用户名失败:", error);
      ElMessage.error("更新用户名失败");
    });
};

const saveUserPhone = () => {
  axios
    .post(
      "http://localhost:8000/UserController/updateUser",
      {
        userPhone: user.value.userPhone,
      },
      { withCredentials: true }
    )
    .then((response) => {
      console.log("手机号已更新:", response.data);
      isEditingPhone.value = false;
      ElMessage.success("手机号已更新");
    })
    .catch((error) => {
      console.error("更新手机号失败:", error);
      ElMessage.error("更新手机号失败");
    });
};

const saveUserEmail = () => {
  axios
    .post(
      "http://localhost:8000/UserController/updateUser",
      {
        useremail: user.value.useremail,
      },
      { withCredentials: true }
    )
    .then((response) => {
      console.log("邮箱已更新:", response.data);
      isEditingEmail.value = false;
      ElMessage.success("邮箱已更新");
    })
    .catch((error) => {
      console.error("更新邮箱失败:", error);
      ElMessage.error("更新邮箱失败");
    });
};

const changePassword = () => {
  if (newPassword.value.length < 6) {
    ElMessage.error("新密码长度不能少于6位");
    return;
  }
  axios
    .post(
      "http://localhost:8000/UserController/updatePassword",
      {
        oldPassword: oldPassword.value,
        newPassword: newPassword.value,
      },
      { withCredentials: true }
    )
    .then((response) => {
      console.log("密码已更新:", response.data);
      oldPassword.value = "";
      newPassword.value = "";
      showPasswordCard.value = false;
      ElMessage.success("密码已更新");
    })
    .catch((error) => {
      console.error("更新密码失败:", error);
      ElMessage.error("更新密码失败");
    });
};

onMounted(() => {
  fetchUserData();
});
const goBack = () => {
  isEditing.value = !isEditing.value;
};
</script>

<style scoped>
.Afont {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
</style>
